<script setup lang="ts">
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CustomNavbar from './components/customNavbar.vue'
import CategoryPanel from './components/categoryPanel.vue'
import HotPanel from './components/hotPanel.vue'
import { ref } from 'vue'
import { useGuessList } from '@/composables/index'
import PageSkeleton from './components/pageSkeleton.vue'
// 获取轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}

// 获取前台分类数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}

// 获取热门推荐数据
const hotList = ref<HotItem[]>([])
const getHomeHotData = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}

//获取猜你喜欢组件实例
const { guessRef, onScrollTolower } = useGuessList()

//下拉刷新是否触发
const itTriggered = ref<boolean>(false)
//自定义下拉刷新被触发
const onrefresherrefresh = async () => {
  //开始动画
  itTriggered.value = true
  // await getHomeBannerData()
  // await getHomeCategoryData()
  // await getHomeHotData()
  // 优化性能，减少用户等待时间
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  itTriggered.value = false
}

// 加载标记
const isLoading = ref<boolean>(false)
// 页面加载
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <!-- 滚动容器 -->
  <scroll-view
    refresher-enabled
    @refresherrefresh="onrefresherrefresh"
    :refresher-triggered="itTriggered"
    @scrolltolower="onScrollTolower"
    class="scroll-view"
    scroll-y
  >
    <!-- 骨架屏 -->
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 自定义轮播图 -->
      <Rabbitswiper :list="bannerList" />
      <!-- 分类面板 -->
      <CategoryPanel :list="categoryList" />
      <!-- 热门推荐 -->
      <HotPanel :list="hotList" />
      <!-- 猜你喜欢 -->
      <Rabbitguess ref="guessRef" />
    </template>
  </scroll-view>
</template>
<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
}
</style>
